package cn.lingyangwl.framework.security.submit;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.DigestUtil;
import cn.lingyangwl.framework.cache.core.service.CacheService;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
public class RepeatSubmitManager {

    @Resource
    private CacheService cacheService;
    @Resource
    private RepeatSubmitDefinition repeatSubmitDefinition;

    /**
     * 获取令牌, 用于令牌防重模式
     */
    public String getToken(long time, TimeUnit unit) {
        String token = UUID.randomUUID().toString();
        String keyPrefix = repeatSubmitDefinition.getKeyPrefix();
        String key = keyPrefix + "::" + DigestUtil.md5Hex(String.format("%s::%s", repeatSubmitDefinition.getUserId().get(), token));
        cacheService.opsForValue().setEx(key, "", time, unit);
        return token;
    }

    public boolean checkToken(String token) {
        String keyPrefix = repeatSubmitDefinition.getKeyPrefix();
        String key = keyPrefix + "::" + DigestUtil.md5Hex(String.format("%s::%s", repeatSubmitDefinition.getUserId().get(), token));
        return cacheService.opsForKey().delete(key);
    }
}
